<!--
 * @Author: fumin 31408026@qq.com
 * @Date: 2025-11-10 15:40:55
 * @LastEditors: fumin 31408026@qq.com
 * @LastEditTime: 2025-11-20 19:10:20
 * @FilePath: /xinjiangkf-miniapp/src/pages/login/login.vue
 * @Description: 微信一键登录页面
-->
<template>
  <view class="login-page">
    <image
      class="page-bg"
      src="/static/images/service-bg.png"
      mode="aspectFill"
    />
    <CustomNavbar title="新疆电信" />
    <view class="page-content">
      <!-- Logo和标题 -->
      <view class="login-header">
        <image
          class="logos"
          src="/static/icons/login-logo.png"
          mode="aspectFit"
        />
        <text class="app-name">中国电信新疆客服</text>
      </view>

      <!-- 登录说明 -->
      <view class="login-intro">
        <text class="intro-text">登录后即可享受完整服务</text>
      </view>

      <!-- 手机号验证码登录表单 -->
      <view class="login-form">
        <!-- 手机号输入框 -->
        <view class="input-group">
          <input
            class="input-field"
            type="number"
            v-model="phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>

        <!-- 验证码输入框 -->
        <view class="input-group code-group">
          <input
            class="input-field code-input"
            type="number"
            v-model="code"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <view
            class="send-code-btn"
            @click="handleSendCode"
            :disabled="!canSendCode || isSendingCode"
          >
            {{ codeButtonText }}
          </view>
        </view>

        <!-- 登录按钮 -->
        <button
          class="login-btn"
          @click="handlePhoneLogin"
          :loading="isLoading"
        >
          <text class="btn-text">登录</text>
        </button>
      </view>

      <!-- 登录按钮区域（暂时隐藏） -->
      <!-- <view class="login-btn-container">
                <button 
                    class="wechat-login-btn" 
                    open-type="getUserInfo" 
                    @click="handleWechatLogin"
                    :loading="isLoading"
                    :disabled="isLoading"
                >
                    <text class="btn-text">微信一键登录</text>
                </button>
                
                <button 
                    class="ctcc-login-btn" 
                    @click="handleCtccLogin"
                    :loading="isLoading"
                    :disabled="isLoading"
                >
                    <text class="btn-text">天翼免密登录</text>
                </button>
            </view> -->

      <!-- 用户协议 -->
      <view class="agreement">
        <text class="agreement-text">登录即表示同意</text>
        <text class="link-text" @click="showAgreement('user')"
          >《用户协议》</text
        >
        <text class="agreement-text">和</text>
        <text class="link-text" @click="showAgreement('privacy')"
          >《隐私政策》</text
        >
      </view>
    </view>
  </view>
</template>

<script setup>
import CustomNavbar from "@/components/CustomNavbar.vue";
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useUserStore } from "@/store/user.js";
import { api } from "@/utils/api.js";
import wechatAuth from "@/utils/wechatAuth.js";
import { onLoad } from "@dcloudio/uni-app";
import { encryptByDESModeCBCUtf8to64 } from '@/utils/crypto.js';
const userStore = useUserStore();
const statusBarHeight = ref(0);
const navBarHeight = ref(88); // 默认值：状态栏(44) + 导航栏(44)
const isLoading = ref(false);

const fromCode = ref("");


// 手机号验证码登录相关
const phone = ref("");
const code = ref("");
const isSendingCode = ref(false);
const countdown = ref(0);
const codeButtonText = ref("发送验证码");
const canSendCode = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && countdown.value === 0;
});

onMounted(async () => {
  // 使用新的 API 获取窗口信息
  const windowInfo = uni.getWindowInfo();
  statusBarHeight.value = windowInfo.statusBarHeight || 0;
  navBarHeight.value = statusBarHeight.value + 64;

  // 检查是否已经登录
  const isLoggedIn = await checkLoginStatus();

  // // #ifdef H5
  // // H5端：如果是微信环境，尝试自动授权登录
  // if (!isLoggedIn && wechatAuth.isWechat()) {
  //   await handleH5WechatAuth()
  // }
  // // #endif

  //H5端 授权登录
  


  // #ifdef H5
  // H5端：如果是微信环境，尝试自动授权登录
  getWechatCode();
  // #endif

});

// 判断是否微信环境
const isWeixinBrowser = () => {
  return /micromessenger/i.test(navigator.userAgent);
};

// 获取微信授权code
const getWechatCode = async () => {
  if (!isWeixinBrowser()) {
    uni.showToast({
      title: "非微信环境,无法登录",
      icon: "none",
    });
    // this.visible = false
    return;
  }

  // 1. 检查URL中是否有code（微信回调时会有）
    const code = getUrlParam("code");
    if (code) {
      // fromCode.value = code;
      //有code 存储本地
      // uni.setStorageSync("authCode", code);
      // clearUrlCode(); // 清除URL中的code参数
      loginWithH5Code(code);
      return;
    }
    const appId = "wx1e43e7581744e421";
    // 2. 没有code则跳转授权http://localhost:8080/xcxchat/#/pages/login/login
    const redirectUri = encodeURIComponent(window.location.href);
    // const redirectUri = encodeURIComponent('https://kf.xj.189.cn/xcxchat/#/pages/login/login');
    // console.log('redirectUri == ', window.location.href)
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;

  // //先尝试从本地获取code
  // let wx_code = uni.getStorageSync("authCode");
  // //如果没有或者过期，重新授权获取
  // if (!wx_code) {
  //   // 1. 检查URL中是否有code（微信回调时会有）
  //   const code = getUrlParam("code");
  //   if (code) {
  //     fromCode.value = code;
  //     //有code 存储本地
  //     uni.setStorageSync("authCode", code);
  //     clearUrlCode(); // 清除URL中的code参数
  //     return;
  //   }
  //   const appId = "wx1e43e7581744e421";
  //   // 2. 没有code则跳转授权http://localhost:8080/xcxchat/#/pages/login/login
  //   const redirectUri = encodeURIComponent(window.location.href);
  //   // const redirectUri = encodeURIComponent('https://kf.xj.189.cn/xcxchat/#/pages/login/login');
  //   // console.log('redirectUri == ', window.location.href)
  //   window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
  // } else {
  //   //如果有就直接 赋值 将你获取到的code存起来 后面要传给后端
  //   //4. 使用code调用getOpenId接口
  //   fromCode.value = wx_code;

  //   loginWithH5Code(wx_code);
  // }
};

//获取回调code
const getUrlParam = (key) => {
  const params = new URLSearchParams(window.location.search);
  return params.get(key);
};

//清理路径上的参数
const clearUrlCode = () => {
  if (window.history.replaceState) {
    const cleanUrl =
      window.location.origin + window.location.pathname + window.location.hash;
    window.history.replaceState({}, "", cleanUrl);
  }
};

// 检查登录状态
const checkLoginStatus = async () => {
  try {
    const userInfo = uni.getStorageSync("userInfo");
    if (userInfo && userInfo.token) {
      // 恢复登录状态
      userStore.isLoggedIn = true;
      userStore.openid = userInfo.openid;
      userStore.token = userInfo.token;

      // 跳转到首页（使用 uni.reLaunch 清空页面栈，防止返回登录页）
      uni.reLaunch({
        url: "/pages/index/index"
      });
      return true;
    }
    return false;
  } catch (error) {
    console.error("检查登录状态失败:", error);
    return false;
  }
};

// H5端微信授权登录
const handleH5WechatAuth = async () => {
  try {
    // 1. 初始化授权流程
    const authResult = await wechatAuth.initAuth();

    if (authResult.needAuth) {
      // 需要授权，跳转到微信授权页面
      console.log("需要微信授权，跳转中...");
      wechatAuth.redirectToAuth();
      return;
    }

    if (authResult.code) {
      // 已有授权code，进行登录
      console.log("获取到授权code，开始登录...");
      await loginWithWechatCode(authResult.code);
    }
  } catch (error) {
    console.error("H5微信授权失败:", error);
    // 授权失败，显示登录表单让用户手动登录
  }
};

const loginWithH5Code = (openid) => {
  // 4. 使用code调用getOpenId接口
  api
    .getOpenId(openid)
    .then((res) => {
      console.log("获取成功openid == ", res.data.openid);
      const userInfo = {
        // token: loginRes.data.token || loginRes.data.accessToken || '',
        openid: res.data.openid || "",
        // phone: loginRes.data.phone || '',
        type: "wechat_oauth", // 标识为微信H5授权登录
      };

      // 更新用户状态
      userStore.isLoggedIn = true;
      userStore.openid = userInfo.openid;
      // userStore.token = userInfo.token
      // userStore.phone = userInfo.phone

      // 保存到本地存储
      uni.setStorageSync("userInfo", userInfo);

      console.log("登录成功，用户信息:", userInfo);

      // // 登录成功提示
      // uni.showToast({
      //   title: "登录成功",
      //   icon: "success",
      //   duration: 1500,
      // });

      // // 延迟跳转，让用户看到成功提示
      // setTimeout(() => {
      //   uni.reLaunch({
      //     url: "/pages/index/index"
      //   });
      // }, 1500);

    })
    .catch((err) => {
      console.log("获取openid失败 == ", err);
    });


};

// 使用微信授权code进行登录
const loginWithWechatCode = async (code) => {
  try {
    isLoading.value = true;

    // 调用后端接口，用code换取token
    const loginRes = await api.wxOAuthLogin({ code: code });

    if (loginRes.code === 0 || loginRes.code === 200) {
      // 登录成功，保存用户信息
      const userInfo = {
        // token: loginRes.data.token || loginRes.data.accessToken || '',
        openid: loginRes.data.openid || "",
        // phone: loginRes.data.phone || '',
        type: "wechat_oauth", // 标识为微信H5授权登录
      };

      // 更新用户状态
      userStore.isLoggedIn = true;
      userStore.openid = userInfo.openid;
      // userStore.token = userInfo.token
      // userStore.phone = userInfo.phone

      // 保存到本地存储
      uni.setStorageSync("userInfo", userInfo);

      // 保存wxphone（如果后端返回）
      if (loginRes.data.phone) {
        uni.setStorageSync("wxphone", loginRes.data.phone);
      }

      // 登录成功提示
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index"
        });
      }, 1500);
    } else {
      throw new Error(loginRes.msg || "登录失败");
    }
  } catch (error) {
    console.error("微信授权登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    isLoading.value = false;
  }
};

// 微信一键登录
const handleWechatLogin = async () => {
  try {
    isLoading.value = true;

    // 1. 获取微信登录code
    const { code } = await uni.login({
      provider: "weixin",
      success: () => {},
      fail: (err) => {
        console.error("获取登录code失败:", err);
        throw new Error("获取登录凭证失败");
      },
    });

    if (!code) {
      throw new Error("获取登录凭证失败");
    }

    // 2. 调用后端登录接口
    const loginRes = await userStore.login(code);

    if (loginRes.code === 0) {
      // 3. 获取用户信息（可选）
      try {
        const { userInfo } = await uni.getUserProfile({
          desc: "用于完善会员资料",
          success: () => {},
          fail: () => {
            console.log("用户拒绝提供信息");
          },
        });

        if (userInfo) {
          // 发送用户信息到后端
          await userStore.setUserInfo(userInfo);
        }
      } catch (err) {
        console.log("获取用户信息失败或用户拒绝:", err);
      }

      // 4. 登录成功，跳转到首页
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index"
        });
      }, 1500);
    } else {
      throw new Error(loginRes.msg || "登录失败");
    }
  } catch (error) {
    console.error("微信登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    isLoading.value = false;
  }
};

// 显示协议
const showAgreement = (type) => {
  uni.showModal({
    title: type === "user" ? "用户协议" : "隐私政策",
    content: type === "user" ? "用户协议内容..." : "隐私政策内容...",
    showCancel: false,
  });
};

// 天翼免密登录
const handleCtccLogin = async () => {
  try {
    isLoading.value = true;

    // 检查是否在电信网络环境
    const networkInfo = await uni.getNetworkType();
    console.log("当前网络类型:", networkInfo.networkType);

    // 调用电信SDK进行免密登录（实际项目中需要集成电信的SDK）
    // 这里模拟获取token或其他凭证
    const ctccToken = "mock_ctcc_token_" + Date.now();

    // 调用后端天翼登录接口
    const loginRes = await api.ctccLogin({ token: ctccToken });

    if (loginRes.code === 0) {
      // 存储用户信息
      const userInfo = {
        token: loginRes.data.token,
        openid: loginRes.data.openid || `ctcc_${Date.now()}`,
        phone: loginRes.data.phone || "",
        type: "ctcc", // 标识为天翼登录
      };

      // 更新用户状态
      userStore.isLoggedIn = true;
      userStore.openid = userInfo.openid;
      userStore.token = userInfo.token;
      userStore.phone = userInfo.phone;

      // 保存到本地存储
      uni.setStorageSync("userInfo", userInfo);

      // 登录成功提示
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index"
        });
      }, 1500);
    } else {
      throw new Error(loginRes.msg || "登录失败");
    }
  } catch (error) {
    console.error("天翼免密登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    isLoading.value = false;
  }
};

// 发送验证码
const handleSendCode = async () => {
  if (!canSendCode.value) {
    return;
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  try {
    isSendingCode.value = true;
    let res;

    // #ifdef H5
    // 公众号登录
    res = await api.sendCodeh5({ phone: phone.value });
    // #endif

    // #ifndef H5
    // 小程序登录
    res = await api.sendCode({ phone: phone.value });
    // #endif

    if (res.code === 0 || res.code === 200) {
      uni.showToast({
        title: "验证码已发送",
        icon: "success",
        duration: 2000,
      });

      // 开始倒计时
      countdown.value = 60;
      startCountdown();
    } else {
      throw new Error(res.msg || "发送验证码失败");
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
    uni.showToast({
      title: error.message || "发送验证码失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    isSendingCode.value = false;
  }
};


// 倒计时
let countdownTimer = null;
const startCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }

  countdownTimer = setInterval(() => {
    countdown.value--;
    codeButtonText.value = `${countdown.value}秒后重发`;

    if (countdown.value <= 0) {
      clearInterval(countdownTimer);
      countdownTimer = null;
      codeButtonText.value = "发送验证码";
    }
  }, 1000);
};

// 手机号验证码登录
const handlePhoneLogin = async () => {
  // 验证手机号
  if (!phone.value || !/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 验证验证码
  if (!code.value || code.value.length !== 6) {
    uni.showToast({
      title: "请输入6位验证码",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  try {
    isLoading.value = true;

    let loginRes;

    // #ifdef H5
    // 公众号登录
    loginRes = await api.toBind({
      userPhone: phone.value,
      type: "2",
      verificationCode: code.value,
    });
    // #endif

    // #ifndef H5
    // 小程序登录
    loginRes = await api.login({
      phone: phone.value,
      code: code.value
    });
    // #endif
    

    console.log("toBind", JSON.stringify(loginRes));

    if (loginRes.code === 0 || loginRes.code === 200) {

      // #ifdef H5

      // #endif

      // #ifndef H5
      // 小程序存储用户信息
      const userInfo = {
        token: loginRes.token || "",
        phone: phone.value,
        // openid: loginRes.data.openid || "",
        type: "phone", // 标识为手机号登录
      };

      // 更新用户状态
      userStore.isLoggedIn = true;
      userStore.phone = phone.value;
      userStore.token = userInfo.token;
      userStore.openid = userInfo.openid;


      var key = "holly12345678Az@";
      var iv = "0392039203920300";
      let cs = userInfo.phone;
      // let cs = "19990409544";18999930691；18129382111
      
      try {
        var param = encryptByDESModeCBCUtf8to64(cs, key, iv);
        console.log('✅ 加密后的数据:', param)
        
        // 存储加密后的手机号，供后续接口使用
        // uni.setStorageSync('wxphone', param)
        uni.setStorageSync("wxphone", param);
        console.log('✅ 已存储加密后的手机号到 wxphone')
        
        // testRequest(param)
      } catch (error) {
        console.error('❌ 加密失败，无法继续:', error)
        // 如果加密失败，可以尝试使用明文（仅用于调试）
        uni.setStorageSync('wxphone', cs)
      }
      // 保存到本地存储
      uni.setStorageSync("userInfo", userInfo);
      // #endif

      // 登录成功提示
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index"
        });
      }, 1500);
    } else {
      throw new Error(loginRes.msg || "登录失败");
    }
  } catch (error) {
    console.error("手机号登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    isLoading.value = false;
  }
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});
</script>

<style scoped>
.login-page {
  position: relative;
  z-index: 1;
  padding-top: calc(var(--status-bar-height) + 44px);
  overflow: hidden;
}

.page-content {
  position: relative;
  z-index: 2;

  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  z-index: -1;
  pointer-events: none;
}

/* Logo和标题样式 */
.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 10rpx;
}

.logos {
  width: 476rpx;
  height: 130rpx;
  margin-bottom: 20rpx;
  /* background: rgba(255, 255, 255, 0.9); */
  /* border-radius: 20rpx; */
  padding: 10rpx;
}

.app-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #1c65f0;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

/* 登录说明 */
.login-intro {
  margin-bottom: 100rpx;
}

.intro-text {
  font-size: 28rpx;
  color: rgba(51, 51, 51, 1);
}

/* 登录按钮区域 */
.login-btn-container {
  width: 100%;
  margin-bottom: 60rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.wechat-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1c65f0;
  color: #fff;
  border: none;
  border-radius: 60rpx;
  height: 96rpx;
  font-size: 32rpx;
  font-weight: 500;
  width: 100%;
}

.wechat-login-btn:active {
  background: #06b156;
}

/* 天翼免密登录按钮 */
.ctcc-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e60012;
  color: #fff;
  border: none;
  border-radius: 60rpx;
  height: 96rpx;
  font-size: 32rpx;
  font-weight: 500;
  width: 100%;
}

.ctcc-login-btn:active {
  background: #b30010;
}

.wechat-icon {
  width: 44rpx;
  height: 44rpx;
  margin-right: 16rpx;
}

.btn-text {
  color: #fff;
  font-size: 32rpx;
}

/* 协议样式 */
.agreement {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  font-size: 24rpx;
  color: rgba(51, 51, 51, 1);
}

.link-text {
  color: #1c65f0;
  margin: 0 8rpx;
}

/* 适配深色背景的加载样式 */
.wechat-login-btn[loading]:after {
  border-color: rgba(255, 255, 255, 0.3);
  border-top-color: #fff;
}

/* 登录表单样式 */
.login-form {
  width: 100%;
  margin-bottom: 60rpx;
}

.input-group {
  margin-bottom: 30rpx;
  background: rgba(255, 255, 255, 1);
  border-radius: 48rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.code-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.input-field {
  width: 100%;
  height: 96rpx;
  font-size: 32rpx;
  color: #333;
  background: transparent;
  border: none;
}

.input-field::placeholder {
  color: #999;
}

.send-code-btn {
  min-width: 180rpx;
  color: rgba(78, 138, 254, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 38rpx;
  padding: 0 20rpx;
  white-space: nowrap;
  flex-shrink: 0;
  border: none;
}

.send-code-btn:disabled {
  min-width: 180rpx;
  color: rgba(78, 138, 254, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 38rpx;
  padding: 0 20rpx;
  white-space: nowrap;
  flex-shrink: 0;
  border: none;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  border: none;
  border-radius: 48rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 48rpx;
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* .login-btn:active {
  background: #1558D0;
}

.login-btn:disabled {
  border-radius: 24px;
background: rgba(78, 138, 254, 1);
} */
</style>
